package cn.mini.mybatis.proxy;

import cn.mini.mybatis.session.SqlSession;

import java.util.HashMap;
import java.util.Map;

public class MapperRegistry {
    // 存储 Mapper 接口和对应的 MapperProxyFactory
    private final Map<Class<?>, MapperProxyFactory<?>> knownMappers = new HashMap<>();

    /**
     * 注册 Mapper 接口
     * @param type Mapper 接口的 Class 对象
     * @param <T> Mapper 接口的类型
     */
    public <T> void addMapper(Class<T> type) {
        knownMappers.put(type, new MapperProxyFactory<>(type));
    }

    /**
     * 获取 MapperProxyFactory
     * @param type Mapper 接口的 Class 对象
     * @param <T> Mapper 接口的类型
     * @return MapperProxyFactory 对象
     */
    @SuppressWarnings("unchecked")
    public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
        if (!knownMappers.containsKey(type)) {
            throw new RuntimeException("Type " + type + " is not known to the MapperRegistry.");
        }
        MapperProxyFactory<T> mapperProxyFactory = (MapperProxyFactory<T>) knownMappers.get(type);
        try {
            return mapperProxyFactory.newInstance(sqlSession);
        }catch (Exception e) {
            throw new RuntimeException("Error getting mapper instance. Cause: " + e, e);
        }
    }

    /**
     * 判断是否包含指定的 Mapper 接口
     * @param type Mapper 接口的 Class 对象
     * @return 如果包含则返回 true，否则返回 false
     */
    public boolean hasMapper(Class<?> type) {
        return knownMappers.containsKey(type);
    }
}
